package yto.freemarker.java8.forkjoin;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 在多数据的情况下的，fork、join效果明显
 *
 * @author dongxing
 * @create 2018-06-23 16:22
 **/
public class TestForkJoin {

    @Test
    public void test1() {

        Instant start = Instant.now();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 1000000000L);

        Long aLong = pool.invoke(task);

        Instant end = Instant.now();

        System.out.println("运行的时间：" + Duration.between(start, end).toMillis());

        System.out.println(aLong);

    }

    @Test
    public void test2() {

        Instant start = Instant.now();

        Long sum = 0L;

        for (int i = 0; i < 1000000000; i++) {
            sum += i;
        }

        Instant end = Instant.now();

        System.out.println("运行时间：" + Duration.between(start, end).toMillis());

    }


    /**
     * java8的并行流
     *
     * 并行流：parallel
     * 串行流：sequential
     */
    @Test
    public void test3() {

        Instant start = Instant.now();

        LongStream.rangeClosed(0, 1000000000L)
                .parallel()
                .reduce(0,Long::sum);

        Instant end = Instant.now();
        System.out.println("时间："+Duration.between(start,end).toMillis());

    }

}
